import accounting from 'accounting';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Popconfirm, Modal } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import moment from 'moment';
import React, { PureComponent } from 'react';
import myStyle from './style.less';

import { PrimaryGhostC, AdvancedSearch, DATA_ENTRY, PrimaryC, TableC, InputNumberC, InfoTipsC } from '../../../comps';
import { exportFile, getUserInfo } from '../../../utils/commonFunc';
import { findValueByCode } from '../../../utils/utils';

@Form.create()
@connect(({ nonstandardValueReviewM, loading, globalM }) => ({ nonstandardValueReviewM, loading, globalM }))
export default class NonstandardValueReviewC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      searchObj: { valuationDate: moment().format('YYYY-MM-DD') },
      columns: [],
      dataSource: [],
      isReset: false, // 是否点击重置
      selectedRowKeys: [], // 勾选的数据
      isEdit: false, // 是否处于编辑状态
      editDataSource: {}, // 编辑前的数据
      isCheck: false, // true:勾选且包含了未复核,false:无勾选或勾选中不包含未复核。  逻辑： 没有勾选未复核的数据，一键确认按钮置灰
      isExportCheck: false, // true:勾选且包含了已复核,false:无勾选或勾选中不包含已复核。  逻辑： 没有勾选已复核的数据，导出按钮置灰
      checkConfirmArr: [], // 一键确认所处理的数据，即已勾选的未复核的数据
      exportArr: [], // 导出所处理的数据，即已勾选的已复核的数据  发送托管人也可以用这
      isConfirmShow: true, // 一键确认的显示隐藏逻辑：仅当天数据展示“一键确认”按钮，非当天日期，隐藏；
      myMsg: '', // 发送
      open: false, // 发送托管人的弹窗是否弹出
    };
  }

  componentDidMount() {
    this.getTableData();
  }

  // 获取表格数据
  getTableData = () => {
    const {
      globalM: {
        dataDictionary: { BAXX_JNTGJGMC = [] },
      },
    } = this.props;
    const { searchObj } = this.state;
    this.setState(
      {
        columns: undefined,
        dataSource: undefined,
        isCheck: false,
        isExportCheck: false,
        selectedRowKeys: [], // 勾选的key集合
        checkConfirmArr: [], // 供一键确认的id集合
        exportArr: [], // 供导出的id集合
      },
      () => {
        this.props.dispatch({
          type: 'nonstandardValueReviewM/getTableData',
          payload: {
            valuationDate: moment().format('YYYY-MM-DD'),
            ...searchObj,
            currentPage: 1,
            numInPage: 999,
            type: this.props.type,
          },
          callback: (type, data) => {
            if (type == 'success') {
              let tempColumns = _.cloneDeep(data.columns);
              if (this.props.type == '1' || this.props.type == '3') {
                // 市价法和成本法
                // 去除组合名称列
                tempColumns = data?.columns?.map((item) => item.dataIndex != 'portfolioName' && item).filter((item) => item);
                tempColumns?.forEach((item) => {
                  if (item.dataIndex == 'productName') {
                    // 产品名称
                    item.width = '12%';
                  }
                  if (item.dataIndex == 'valuationId') {
                    // 产品估值代码
                    // item.width = '10%'
                    item.width = '12%';
                  }
                  if (item.dataIndex == 'custodianId') {
                    // 托管人
                    item.ellipsis = true;
                    item.render = (text) => {
                      if (text == null || text == undefined) {
                        return '--';
                      }
                      return findValueByCode(text, BAXX_JNTGJGMC);
                    };
                  }
                  if (item.dataIndex == 'assetType') {
                    // 资产类型
                    // item.width = '10%'
                    item.width = '9%';
                  }
                  if (item.dataIndex == 'secuabbr') {
                    // 证券名称
                    item.ellipsis = true;
                  }
                  if (item.dataIndex == 'tradingCode') {
                    // 证券代码
                    item.width = '10%';
                  }
                  if (item.dataIndex == 'reviewStatus') {
                    // 复核状态
                    item.width = '10%';
                  }
                  if (item.dataIndex == 'valuationPrice') {
                    // 估值结果
                    item.width = '13%';
                    item.align = 'right';
                    item.render = (text) => {
                      if (text === null || text === undefined) {
                        return '--';
                      }
                      // eslint-disable-next-line no-restricted-globals
                      if (isNaN(text)) {
                        return text;
                      }
                      return accounting.formatNumber(Number(text), 4); // 数字默认无小数位，需要小数位自行传入
                    };
                  }
                });
              } else {
                data.columns?.forEach((item) => {
                  if (item.dataIndex == 'productName') {
                    // 产品名称
                    item.width = '12%';
                  }
                  if (item.dataIndex == 'portfolioName') {
                    // 组合名称
                    item.width = '12%';
                  }
                  if (item.dataIndex == 'assetType') {
                    // 资产类型
                    item.width = '12%';
                  }
                  if (item.dataIndex == 'tradingCode') {
                    // 证券代码
                    item.width = this.state.isConfirmShow ? '10%' : '15%';
                  }
                  if (item.dataIndex == 'reviewStatus') {
                    // 复核状态
                    item.width = '10%';
                  }
                  if (item.dataIndex == 'valuationPrice') {
                    // 估值结果
                    item.width = this.state.isConfirmShow ? '12%' : '17%';
                    item.align = 'right';
                    item.render = (text) => {
                      if (text === null || text === undefined) {
                        return '--';
                      }
                      // eslint-disable-next-line no-restricted-globals
                      if (isNaN(text)) {
                        return text;
                      }
                      return accounting.formatNumber(Number(text), 4); // 数字默认无小数位，需要小数位自行传入
                    };
                  }
                });
              }
              let arr;
              if (this.props.allUnConfirm) arr = data.dataSource.filter((item) => item.reviewStatus == '未复核');
              this.setState({
                // columns: data.columns,
                columns: this.props.type == '2' ? data.columns : tempColumns,
                dataSource: arr || data.dataSource,
              });
            }
          },
        });
      },
    );
  };

  // 查询
  queryTableList = (e) => {
    const tempQuery = {};
    // eslint-disable-next-line no-unused-vars
    for (const k in e) {
      if (k == 'valuationDate') {
        tempQuery[k] = e[k].format('YYYY-MM-DD');
      } else {
        tempQuery[k] = e[k];
      }
    }
    this.setState(
      {
        searchObj: tempQuery,
        isReset: false,
        currentPage: 1,
        numInPage: 999,
      },
      () => {
        if (this.state.searchObj?.valuationDate != moment().format('YYYY-MM-DD')) {
          // 仅当天数据展示“一键确认”按钮，非当天日期，隐藏
          this.setState({
            isConfirmShow: false,
          });
        } else {
          this.setState({
            isConfirmShow: true,
          });
        }
        this.getTableData();
      },
    );
  };

  // 勾选事件
  onSelectChange = (selectedRowKeys) => {
    // 存放勾选中未复核的数据id
    const resultArr = [];
    // 存放勾选中已复核的数据id
    const exportResultArr = [];

    this.setState({ selectedRowKeys }, () => {
      if (this.state.selectedRowKeys?.length > 0) {
        // 一键确认 是否置灰逻辑处理 resultArr:存放勾选中 状态为未复核的数据
        this.state.selectedRowKeys &&
          this.state.selectedRowKeys.length &&
          this.state.selectedRowKeys.forEach((item) => {
            this.state.dataSource &&
              this.state.dataSource.length &&
              this.state.dataSource.forEach((dataItem) => {
                if (dataItem.id == item && dataItem.reviewStatus == '未复核') {
                  resultArr.push(item);
                }
                if (dataItem.id == item && dataItem.reviewStatus == '已复核') {
                  exportResultArr.push(item);
                }
              });
          });
        this.setState({
          checkConfirmArr: resultArr,
          exportArr: exportResultArr,
          isCheck: !!resultArr.length,
          isExportCheck: !!exportResultArr.length,
        });
      } else {
        this.setState({
          isCheck: false,
          isExportCheck: false,
          checkConfirmArr: [],
          exportArr: [],
        });
      }
    });
  };

  // 编辑事件
  editItem = (recordId) => {
    this.setState(
      {
        isEdit: true, // 表格处于编辑状态
      },
      () => {
        this.changeColumns(recordId, 'editable');
      },
    );
  };

  // 保存事件
  saveItem = (recordId) => {
    const {
      form: { validateFields },
    } = this.props;
    const { searchObj } = this.state;
    validateFields((err, fieldsValue) => {
      if (!err) {
        this.props.dispatch({
          type: 'nonstandardValueReviewM/changeValue',
          payload: {
            valuationDate: searchObj.valuationDate,
            id: recordId,
            valuationPrice: fieldsValue.valuationPrice,
            type: this.props.type,
          },
          callback: (type) => {
            if (type == 'success') {
              this.getTableData();
              this.setState({ isEdit: false });
            }
          },
        });
      } else {
        message.error('请输入估值结果');
      }
    });
  };

  // 取消事件
  cancelItem = (recordId) => {
    this.setState({ isEdit: false });
    this.changeColumns(recordId, 'none');
  };

  // 更改columns，添加和更改属性来实现可编辑单元格
  changeColumns = (id, type) => {
    const { columns, dataSource, editDataSource } = this.state;
    const arr = dataSource.filter((item) => item.id == id); // 根据id查找该条数据
    const index = dataSource.findIndex((item) => item.id == id); // 查找数据位置
    if (type == 'editable') {
      // 编辑状态，估值结果变为可编辑的单元格
      // 编辑前保存该数据，防止取消后数据更改
      // eslint-disable-next-line no-shadow
      const editDataSource = _.cloneDeep(arr[0]);
      this.setState({
        editDataSource,
      });

      dataSource.map((item) => (item.isDisabled = true)); // 当有一条数据处于编辑状态时，其他数据不可编辑
      arr[0].isEdit = true;
      dataSource.splice(index, 1, arr[0]);
    } else if (type == 'none') {
      // 非编辑状态，还原
      arr[0].isEdit = undefined;
      arr[0].valuationPrice = editDataSource.valuationPrice;
      dataSource.map((item) => (item.isDisabled = undefined));
      dataSource.splice(index, 1, arr[0]);
    }
    columns &&
      columns.length &&
      columns.forEach((item) => {
        if (item.key == 'valuationPrice') {
          item.render = (text, record) => {
            if (text === null || text === undefined) {
              return '--';
            }
            // eslint-disable-next-line no-restricted-globals
            if (isNaN(text)) {
              return text;
            }
            if (record.isEdit) {
              return (
                <InputNumberC
                  form={this.props.form}
                  dataIndex='valuationPrice'
                  splitStyle={true}
                  min={0}
                  initialValue={record.valuationPrice}
                  precision={4}
                  rules={[{ required: true, message: ' ' }]}
                />
              );
            }
            return Number(text).toFixed(4);
          };
        }
      });
    this.setState({
      columns,
    });
  };

  // 一键确认
  confirmClick = () => {
    const { searchObj, checkConfirmArr, dataSource } = this.state;
    // 勾选的数据中是否有正在编辑的状态
    let flag = false;
    checkConfirmArr &&
      checkConfirmArr.length &&
      checkConfirmArr.forEach((selectItem) => {
        dataSource &&
          dataSource.length &&
          dataSource.forEach((item) => {
            if (item.id == selectItem && item.isEdit) {
              flag = true;
            }
          });
      });
    if (!flag) {
      let tempDate = moment().format('YYYY-MM-DD');
      if (searchObj && JSON.stringify(searchObj) != '{}') {
        tempDate = searchObj.valuationDate;
      }
      this.props.dispatch({
        type: 'nonstandardValueReviewM/groupConfirm',
        payload: {
          valuationDate: tempDate,
          reviewDatas: checkConfirmArr,
          type: this.props.type,
        },
        callback: (type) => {
          if (type == 'success') {
            this.getTableData();
          }
        },
      });
    } else {
      // 编辑状态,
      message.warning('请保存您编辑的信息后再操作。');
    }
  };

  // 导出
  export = () => {
    const { searchObj, exportArr, dataSource } = this.state;
    // 勾选的数据中是否有正在编辑的状态
    let flag = false;
    exportArr &&
      exportArr.length &&
      exportArr.forEach((selectItem) => {
        dataSource &&
          dataSource.length &&
          dataSource.forEach((item) => {
            if (item.id == selectItem && item.isEdit) {
              flag = true;
            }
          });
      });

    if (!flag) {
      let tempDate = moment().format('YYYY-MM-DD');
      if (searchObj && JSON.stringify(searchObj) != '{}') {
        tempDate = searchObj.valuationDate;
      }
      const params = {
        valuationDate: tempDate,
        type: this.props.type,
        reviewDatas: exportArr.join(),
      };
      if (searchObj?.custodianId != undefined) params.custodianId = searchObj?.custodianId;
      exportFile('api/v1/nonstandardValuationReview/exportNonValuationReviewAcmList', params);
    } else {
      // 编辑状态,
      message.warning('请保存您编辑的信息后再操作。');
    }
  };

  // info提示
  infoContent = () => <div>当天的估值结果会在每日日终07:15提供。</div>;

  // 计算点击事件
  calculateClick = () => {
    const userInfo = getUserInfo();
    if (!userInfo.isSuper) {
      this.props.dispatch({
        type: 'nonstandardValueReviewM/calculateData',
        payload: {
          date: moment().format('YYYY-MM-DD'),
          tenant: userInfo.tenantName,
          type: this.props.type,
        },
        callback: (type) => {
          if (type == 'success') {
            this.getTableData();
          }
        },
      });
    }
  };

  // 发送托管人表格 给后端
  confirmPost = () => {
    const { exportArr } = this.state;
    this.props.dispatch({
      type: 'nonstandardValueReviewM/postList',
      payload: [...exportArr],
      callback: () => {
        // 发送成功 取消勾选 跟勾选相关的变量 重置
        this.setState({
          selectedRowKeys: [],
          exportArr: [],
          isCheck: false,
          isExportCheck: false,
          checkConfirmArr: [],
        });
      },
    });
    this.onCancel();
  };

  handleOpenChange = (newOpen) => {
    if (!newOpen) {
      // 关闭的时候 不做处理
      this.setState({
        open: newOpen,
      });
      return;
    }
    const { selectedRowKeys, exportArr, dataSource } = this.state;
    console.log(selectedRowKeys, exportArr);
    if (selectedRowKeys?.length != exportArr?.length) {
      // 如果勾选的数据和 已复核的数据 不相等，则提示用户 不能发送
      message.warning('勾选未复核资产，发送失败；请先确认估值结果！');
      return;
    }
    const temp1 = dataSource.filter((item) => item.reviewStatus == '已复核');
    const temp2 = dataSource.filter((item) => item.reviewStatus != '已复核');
    let myMsg = '';
    if (temp2?.length) {
      myMsg = '有未复核资产，是否仍要发送?';
    } else if (temp1?.length == dataSource?.length && temp1.length != exportArr?.length) {
      myMsg = '有已复核资产未勾选，是否仍要发送?';
    }
    this.setState(
      {
        myMsg,
      },
      () => {
        if (this.state.myMsg) {
          // 有场景需要是否弹窗 则设置打开
          this.setState({
            open: newOpen,
          });
        } else {
          // 不需要弹窗 则直接请求
          this.confirmPost();
        }
      },
    );
  };

  // 取消发送托管人确认弹窗
  onCancel = () => {
    this.setState({
      open: false,
      myMsg: '',
    });
  };

  render() {
    const { columns, dataSource, selectedRowKeys, isCheck, isExportCheck, exportArr, open, myMsg } = this.state;
    const { type } = this.props;
    if (
      columns?.length &&
      columns[columns?.length - 1].title != '操作'
      // && isConfirmShow
    ) {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: '10%',
        operates: [
          {
            title: '编辑',
            onClick: (record) => {
              this.editItem(record.id);
            },
            rules: {
              // 某条数据处于编辑状态，其他数据操作被禁用
              disabled: {
                items: [{ key: 'isDisabled', value: [undefined], relation: ['!='] }],
              },
              // 点击编辑时隐藏编辑和删除按钮，展示保存和取消按钮
              hide: {
                relation: 'or',
                items: [
                  { key: 'isEdit', value: [undefined], relation: ['!='] },
                  // 未复核的数据才可以编辑
                  // { key: 'reviewStatus', value: ['已复核'], relation: ['='] },
                ],
              },
            },
          },
          {
            title: '保存',
            onClick: (record) => {
              this.saveItem(record.id);
            },
            rules: {
              // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
            },
          },
          {
            title: '取消',
            onClick: (record) => {
              this.cancelItem(record.id);
              // eslint-disable-next-line max-lines
            },
            rules: {
              // 点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
            },
          },
        ],
      });
    }
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'valuationDate',
          title: '估值日期',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(),
          allowClear: false,
        },
        {
          dataIndex: 'custodianId',
          positionBody: true,
          title: '托管人',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: this.props.custodianList || [],
          filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
        },
      ],
      // 点击查询按钮
      onQuery: (e) => {
        this.queryTableList(e);
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
        });
      },
    };
    // 勾选
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const tenant = localStorage.getItem('antd-pro-tenant');
    return (
      <div>
        <div style={{ marginBottom: '10px' }}>
          <AdvancedSearch {...searchProps} />
        </div>
        <div className={myStyle.operateInfo}>
          <div>
            <Popconfirm title='是否确认？' icon={<QuestionCircleOutlined />} onConfirm={this.confirmClick}>
              <PrimaryC title='一键确认' disabled={!isCheck} />
            </Popconfirm>
          </div>
          {type === '3' ? (
            <Popconfirm
              title={myMsg}
              icon={<QuestionCircleOutlined />}
              open={open}
              onOpenChange={this.handleOpenChange}
              onConfirm={this.confirmPost}
              onCancel={this.onCancel}
              okText='是'
              cancelText='否'
            >
              <PrimaryC
                disabled={!exportArr?.length || !['WXNSH', 'HTSC-TEST'].includes(tenant)}
                loading={this.props.loading.effects['nonstandardValueReviewM/postList']}
                style={{ marginLeft: '10px' }}
                title='发送托管人'
              />
            </Popconfirm>
          ) : null}
          {this.props.type == '1' ? (
            // 市值法下提示
            <div className={myStyle.infoTip}>
              <InfoTipsC Left={this.infoContent()} width='100%' style={{ paddingLeft: '20px' }} />
            </div>
          ) : (
            <div className={myStyle.infoTip} />
          )}
          <div style={{ marginRight: '10px' }}>
            <PrimaryGhostC
              title='计算'
              // disabled={!isConfirmShow}
              onClick={this.calculateClick}
              loading={this.props.loading.effects['nonstandardValueReviewM/calculateData']}
            />
          </div>
          <div style={{ marginRight: '10px' }}>
            <Popconfirm title={'仅导出"已复核"的数据'} icon={<QuestionCircleOutlined />} onConfirm={this.export}>
              <PrimaryGhostC title='导出' disabled={!isExportCheck} />
            </Popconfirm>
          </div>
        </div>
        <div>
          <TableC columns={columns} dataSource={dataSource} hidePage={true} rowKey='id' scroll={{ x: '100%', y: 600 }} rowSelection={rowSelection} bigTable={true} />
        </div>
      </div>
    );
  }
}
